package com.abxh.core;

import com.google.gson.Gson;
import com.tencent.mmkv.MMKV;

/**
 * Created by dab on 2021/8/30 15:17
 */

public class MmkvHelper {
    private static MMKV mmkv;
    private Gson gson = new Gson();

    public Gson getGson() {
        if (gson == null) {
            gson = new Gson();
            return gson;
        }
        return gson;
    }

    private MmkvHelper() {
        mmkv = MMKV.defaultMMKV();
    }

    private MmkvHelper(String mmkvWithID) {
        mmkv = MMKV.mmkvWithID(mmkvWithID);
    }

    public static MmkvHelper getInstance() {
        final MmkvHelper INSTANCE = new MmkvHelper();
        return INSTANCE;
    }

    public static MmkvHelper getInstance(String mmkvWithID) {
        final MmkvHelper INSTANCE = new MmkvHelper(mmkvWithID);
        return INSTANCE;
    }

    public MMKV getMmkv() {
        return mmkv;
    }

    /*********基础类型存储*****************/

    public void putInt(String key, int value) {
        mmkv.encode(key, value);
    }

    public int getInt(String key, int value) {
        return mmkv.decodeInt(key, value);
    }

    public void putBoolean(String key, Boolean value) {
        mmkv.encode(key, value);
    }

    public void putLong(String key, long value) {
        mmkv.encode(key, value);
    }

    public void putFloat(String key, float value) {
        mmkv.encode(key, value);
    }

    public void putString(String key, String value) {
        mmkv.encode(key, value);
    }

    public void putDouble(String key, Double value) {
        mmkv.encode(key, value);
    }

    public Boolean getBoolean(String key, Boolean value) {
        return mmkv.decodeBool(key);
    }

    public float getFloat(String key, float value) {
        return mmkv.decodeFloat(key, value);
    }

    public String getString(String key, String value) {
        return mmkv.decodeString(key, value);
    }

    public String getString(String key) {
        return mmkv.decodeString(key);
    }

    public Double getDouble(String key) {
        return mmkv.decodeDouble(key);
    }

    public Double getDouble(String key, Double value) {
        return mmkv.decodeDouble(key, value);
    }

    public long getLong(String key) {
        return mmkv.decodeLong(key);
    }

    public long getLong(String key, long value) {
        return mmkv.decodeLong(key, value);
    }

    /*********对象类型存储*****************/
    public void putObject(String key, Object value) {
        String jsonString = getGson().toJson(value);
        mmkv.encode(key, jsonString);
    }

    /**
     * 将Json字符串转换为实例
     */
    public <T> T getObject(String key, Class<T> t) {
        return getGson().fromJson(mmkv.decodeString(key), t);
    }

}
